package com.cc.visitor.service;

import com.cc.visitor.dao.JsapiTicketMapper;
import com.cc.visitor.entity.JsapiTicket;
import com.cc.visitor.entity.wechat.WxAccessToken;
import com.cc.visitor.utils.RestTemplateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author chanchaw
 * @create 2025-01-18 15:51
 */
@Service
public class JsapiTicketServiceImpl implements JsapiTicketService{
    private static final String URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
    @Autowired
    private WxAccessToken wxAccessToken;
    @Autowired
    private RestTemplateUtils restTemplateUtils;
    @Autowired
    private JsapiTicketMapper dao;
    @Autowired
    private JsapiTicketServiceImpl meService;

    /**
     * 先从DB获取有效的 ticket，如果没有则请求新的并且缓存到DB
     * @return
     */
    @Override
    public JsapiTicket getActiveTicket() {
        JsapiTicket ticket = dao.getActiveTicket();
        if(ticket != null) return ticket;// 数据库中缓存的有效ticket，直接返回

        String url = URL.replace("ACCESS_TOKEN", wxAccessToken.getAccessToken());
        JsapiTicket ret = restTemplateUtils.get4Object(url, JsapiTicket.class);
        if(ret == null) return ret;
        dao.insert(ret);// 请求来新的ticket则要写入数据库缓存起来
        return ret;
    }


}
